package com.arceus.leetcode;

/**
 * @author : iron
 * @version : 1.0.0
 * @date : 4:02 PM 2018/11/13
 * <p>
 * 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
 * <p>
 * 你可以假设除了数字 0 之外，这两个数字都不会以零开头。
 * <p>
 * 示例：
 * <p>
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 */

public class T2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        String num1 = listToInt("", l1);
        String num2 = listToInt("", l2);
        String res = add(num1, num2);
        char[] chars = res.toCharArray();


        ListNode last = new ListNode(chars[0] - '0');

        for (int i = 1; i < chars.length; i++) {
            ListNode listNode = new ListNode(chars[i] - '0');
            listNode.next = last;
            last = listNode;
        }
        return last;
    }

    String add(String a, String b) {
        int aLength = a.length();
        int bLength = b.length();
        int maxLength = (aLength > bLength) ? aLength : bLength;
        int minLength = (aLength < bLength) ? aLength : bLength;
        String strTmp = "";
        for (int i = maxLength - minLength; i > 0; i--) {
            strTmp += "0";
        }

        // 补足长度
        if (maxLength == aLength) {
            b = strTmp + b;
        } else {
            a = strTmp + a;
        }

        int carryBit = 0;
        String str = "";

        for (int i = maxLength - 1; i >= 0; i--) {
            int aNum = Integer.parseInt(String.valueOf(a.charAt(i)));
            int bNum = Integer.parseInt(String.valueOf(b.charAt(i)));
            int temp;
            if (aNum + bNum + carryBit >= 10 && i != 0) {
                temp = aNum + bNum + carryBit - 10;
                carryBit = 1;
            } else {
                temp = aNum + bNum + carryBit;
                carryBit = 0;
            }
            str = String.valueOf(temp) + str;
        }
        return str;
    }

    public String listToInt(String num, ListNode listNode) {
        num = String.valueOf(listNode.val) + num;
        if (listNode.next != null) {
            num = listToInt(num, listNode.next);
        }
        return num;
    }

    public static void main(String[] args) {

        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(3);

        T2 t2 = new T2();
        System.out.println(t2.addTwoNumbers(listNode, listNode));
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}